package com.smm.web.vmc.handler;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

public class MyDecoder extends CumulativeProtocolDecoder {

    private final CharsetDecoder charsetDecoder;
    public MyDecoder(String _charsetName){
        this.charsetDecoder = Charset.forName(_charsetName).newDecoder();
    }
    @Override
    protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
        String msg = "";
        int fieldSize = 0;
        IoBuffer buffer = IoBuffer.allocate(100).setAutoExpand(true);
        while(in.hasRemaining()){
            byte b = in.get();
            buffer.put(b);
            fieldSize++;
            //10==b表示换行：该短信协议解码器使用\n（ASCII的字符10）作为分界点
            if(10 == b){
                //limit=position，position=0
                buffer.flip();
                //最后的换行符不需要，所以要少读一个字节
                msg = buffer.getString(fieldSize-1, this.charsetDecoder);
                break;
            }
        }
        out.write(msg);
        return false;
    }
}
